package com.easyboot.framework.shiro.stateless;

import cn.hutool.json.JSONUtil;
import com.easyboot.constant.CookieConstants;
import com.easyboot.framework.shiro.UserOwnInfo;
import com.easyboot.utils.EncryptUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author yushuo
 * @className 在登录的情况下会走此方法，此方法返回true直接访问控制器
 * @descripton 无状态验证，禁用seesion,启用cookie验证
 * @date 2021/2/8 10:18
 **/
public class StatelessAuthcFilter extends AccessControlFilter {



    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
       // System.err.println("isAccessAllowed:"+ LocalDateTime.now().toString());
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = this.getCookies(httpServletRequest);
       // System.err.println("------isAccessAllowed--------token:"+token);
        if (StringUtils.hasText(token)) {
            token= EncryptUtils.desDecrypt(token);
            UserOwnInfo userOwnInfo= JSONUtil.toBean(token,UserOwnInfo.class);
            StatelessToken loginAuthToken = new StatelessToken(userOwnInfo);
            // 提交给realm进行登入，如果错误他会抛出异常并被捕获
            getSubject(request, response).login(loginAuthToken);
            // 如果没有抛出异常则代表登入成功，返回true
            return true;
        }
        System.err.println("---------isAccessAllowed-----token:false end");
        return false;
    }


    /**
    *
     * @author yushuo
     * @description 没有登录的情况下会走此方法
     * @date 11:00 2021/2/8
     * @param [request, response]
     * @return boolean
    **/
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        onLoginFail(request,response);
        return false;
    }

    /**
    *
     * @author yushuo
     * @description 登录失败时默认返回401状态码
     * @date 10:35 2021/2/8
     * @param [response]
     * @return void
    **/
    private void onLoginFail(ServletRequest request, ServletResponse response) throws IOException {
        redirectToLogin(request, response);
    }



    private String getCookies(HttpServletRequest request){

        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(CookieConstants.LOGIN_COOKIE_NAME)){
                    try {
                        return URLDecoder.decode(cookie.getValue(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        return null;
                    }
                }
            }
        }

        return  null;
    }

}
